<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :ok-button-props="{ props: { disabled: this.showable } }"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <form-tools
          ref="formTools"
          :formObj="formObj"
        />
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { FormMixin } from '@/mixins/FormMixin'
import formTools from '@/components/BizTools/FormTools'
import pick from 'lodash.pick'
export default {
  name: 'BziForm',
  mixins: [FormMixin],
  components: {
    formTools
  },
  props: {
    formObj: {
      type: Object,
      default: function () {
        return {}
      }
    },
    data: {
      type: Function,
      required: true
    }
  },
  data () {
    return {
      form: this.$form.createForm(this),
      confirmLoading: false
    }
  },
  methods: {
    edit (id, type) {
      this.visible = true
      const { form: { setFieldsValue, resetFields } } = this
      if (['edit', 'show'].includes(type)) {
        this.confirmLoading = true
        const result = this.data(id)
        if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
          result.then(r => {
            this.$nextTick(() => {
              const item = this.formObj.columns.map(item => {
                return item.value
              })
              setFieldsValue(pick(r, item))
            })
          })
        }
        this.confirmLoading = false
      } else {
        resetFields()
      }
    },
    handleOk () {
      this.form.validateFields(async (err, values) => {
        if (!err) {
          this.confirmLoading = true
          try {
            this.$emit('submit', values, this.type, this.done)
          } catch (e) {
            this.$message.error(e.msg)
            this.confirmLoading = false
          }
        }
      })
    },
    done () {
      this.confirmLoading = false
      this.visible = false
    }
  }

}
</script>

<style scoped>

</style>
